package br.com.bbcalibracao.action;

import java.io.OutputStream;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import br.com.bbcalibracao.bean.CalibracaoPdf;
import br.com.bbcalibracao.dao.CalibracaoDAO;
import br.com.bbcalibracao.util.Formatador;
import br.com.bbcalibracao.util.Validador;

public class DownloadPdfAction extends org.apache.struts.action.Action {

    /**
     * This is the action called from the Struts framework.
     *
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
	@Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        
        try {
	        HttpSession sessao = request.getSession();
	        if (Validador.validaSessao(sessao)){
	        	int id = Integer.parseInt((String) request.getParameter("id"));
	        	String nomeArquivo = (String) request.getParameter("nomeArquivo");
	        	if (id!=0 && nomeArquivo!=null && !nomeArquivo.equals("")){
	        		CalibracaoPdf cal = obtemCalibracaoPdf(id, nomeArquivo);
	        		
	        		 
	        		byte[] bytes = cal.getConteudo();  
	        		
	        		String nomeArq = "Calibracao_" + Formatador.formatarDataArquivo(new Date()) + ".pdf";
	        		response.setContentType("application/pdf");  
			        response.setHeader( "Content-disposition", "inline; filename=\""+nomeArq+"\"" );
        			response.setContentLength(bytes.length);  
        			OutputStream outputStream = response.getOutputStream(); 
        			outputStream.write(bytes, 0, bytes.length);  
        			outputStream.flush();  
        			outputStream.close();  
	        		
	        	}
	        } 
	        return null;
        } catch (Exception e) {
        	e.printStackTrace();
        	return null;
		}
        
    }
	
	public CalibracaoPdf obtemCalibracaoPdf(int id, String nomeArquivo){
		CalibracaoDAO cDao = new CalibracaoDAO();
		CalibracaoPdf cal = cDao.obtemCalibracaoPdf(id, nomeArquivo);
		return cal;
    }
}
